/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.games.esmi.ieat.indicatorrelations;

import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.Tree;
import com.vaadin.ui.VerticalLayout;
import eu.games.esmi.ieat.indicatorrelations.data.AssociationRuleMiner;
import eu.games.esmi.ieat.indicatorrelations.data.AssociationRuleMiner.GmsAssRule;
import eu.games.esmi.ieat.indicatorrelations.ui.DatePopupInputPrompt;
import eu.games.esmi.ieat.indicatorrelations.ui.FloatingPointTextField;
import eu.games.esmi.ieat.indicatorrelations.ui.NumericTextField;
import eu.games.esmi.ieat.indicatorvalues.IndicatorTreeGenerator;
import eu.games.esmi.ieat.indicatorvalues.data.EMF;
import it.polimi.games.epkb.entityClasses.StoredValues;
import it.polimi.games.epkb.manager.EPKBmanager;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Set;
import weka.core.Utils;

/**
 *
 * @author user
 */
public class AssociationDesignTab extends Panel {

    public NumericTextField sampling = new NumericTextField("Sampling period (sec)", 30);
//    public DatePopupInputPrompt start = new DatePopupInputPrompt("Start time", new Date(new Date().getTime() - 500 * sampling.getNumber() * 1000));
//    public DatePopupInputPrompt end = new DatePopupInputPrompt("End time", new Date());
    public DatePopupInputPrompt start = new DatePopupInputPrompt("Start time", new GregorianCalendar(2012,5,12,17,0,0).getTime());
    public DatePopupInputPrompt end = new DatePopupInputPrompt("End time", new GregorianCalendar(2012,5,12,18,0,0).getTime());
    public FloatingPointTextField support = new FloatingPointTextField("Minimum support", 0.1);
    public FloatingPointTextField confidence = new FloatingPointTextField("Minimum confidence", 0.3);
    public Tree indicatorTree = new IndicatorTreeGenerator().createTree(IndicatorTreeGenerator.INDICATOR_TREE);
    public TextArea definedAssociationsTextArea = new TextArea("Defined associations");
    
    private String separator = "\n\r";
 
    public AssociationDesignTab() {
        super();
        init();
    }
    
    public void init() {

        HorizontalLayout h = new HorizontalLayout();
        h.setSpacing(true);
        
        //HorizontalLayout h1 = new DragDropTableTree();
        HorizontalLayout h1 = new HorizontalLayout();
        h1.setSpacing(true);
        
            h1.addComponent(indicatorTree);
        
            Button addButton = new Button("Add");
            addButton.addListener(new Listener() {

                public void componentEvent(Event event) {
                //PROVA
                //Tabs.INSTANCE.correlationAnalysisTab.addCorrelationToTable(new Correlation("[PROVA] Sampling time", sampling.getNumber().toString()));
                    for (Object indicator : ((Set<Object>)indicatorTree.getValue()).toArray()) {
                        addToDefinedAssociation(indicator.toString());
                    }
                }
            });
            h1.addComponent(addButton);
            
            definedAssociationsTextArea.setHeight(320, Sizeable.UNITS_PIXELS);
            h1.addComponent(definedAssociationsTextArea);

            VerticalLayout v11 = new VerticalLayout();
            v11.setSpacing(true);

                Button deleteButton = new Button("Delete");
                deleteButton.addListener(new Listener() {
                    public void componentEvent(Event event) {
                        definedAssociationsTextArea.setValue("") ;
                    }
                });
                v11.addComponent(deleteButton);
                
                Button startButton = new Button("Start");
                startButton.addListener(new Listener() {
                    
                    public void componentEvent(Event event) {
                        
                        EPKBmanager epkb = new EPKBmanager(EMF.PU_NAME);
                        long startTime = start.getDatetime().getTime();
                        long endTime = end.getDatetime().getTime();
                        long samplingTime = sampling.getNumber().longValue() * 1000;
                        MainIndicatorRelations.getAssociationAnalysisTab().clearAssociationTable();
                        AssociationRuleMiner miner = new AssociationRuleMiner();
                        for(String indicator : ((String)(definedAssociationsTextArea.getValue())).split(separator)) {
                            List<String> colorList = new ArrayList<String>();
                            List<Long> delta = new ArrayList<Long>();
                            for (long t = startTime; t < endTime; t = t + samplingTime) {
                                System.out.print(new Date(t) + " >>> " + indicator);
                                StoredValues storedvalue = epkb.getIndicator(indicator.split("-")[0], indicator.split("-")[1], new Date(t));
                                colorList.add(storedvalue.getRed()?"red":(storedvalue.getYellow()?"yellow":"green"));
                                delta.add(storedvalue.getDefinitionTime().getTime() - t);
                                System.out.println(": " + (storedvalue.getRed()?"red":(storedvalue.getYellow()?"yellow":"green")));
                            }
                            String[] colors = new String[colorList.size()];
                            for (int i = 0; i < colors.length; i++) {
                                colors[i] = colorList.get(i);
                            }
                            miner.load(indicator, colors);
                            System.out.println("=== Loaded: " + indicator);
                        }
                        
                        String maximumNumberOfRules = "1000";
                        String minumumConfidence = confidence.getNumber() + "";
                        String minimumSupport = support.getNumber() + "";
        
                        String[] options = {
                            "-N",maximumNumberOfRules,
                            "-C",minumumConfidence,
                            "-M",minimumSupport 
                        };
        
                        //set options and mine associations
                        miner.mineAssociations(options);
        
                        //get all the extracted rules as a big string to show, for instance, into a text box
                        String associationRulesString = miner.getAssociationRulesString();

                        //output the association rules as string
                        System.out.println("Miner output:\n"+associationRulesString);
        
                        //output rule by rule
                        GmsAssRule[] rules = miner.getAssociationRulesArray();

                        for (int i = 0; i < rules.length; i++) {
                            MainIndicatorRelations.getAssociationAnalysisTab().addAssociationToTable(
                                    rules[i].getAntecedent().toString(miner.getInstances()) + " ==> " + rules[i].getConsequent().toString(miner.getInstances()),
                                    Utils.doubleToString(rules[i].getConfidence(),2),
                                    Utils.doubleToString(rules[i].getSupport(),2)); 
                        }

                        getWindow().showNotification("Association data available");
                    }
                });
                v11.addComponent(startButton);

            h1.addComponent(v11);

        h.addComponent(h1);
        
        HorizontalLayout h2 = new HorizontalLayout();
            h2.setSpacing(true);
        
            VerticalLayout v21 = new VerticalLayout();
            v21.setSpacing(true);

                v21.addComponent(start);
                
                v21.addComponent(end);

                v21.addComponent(sampling);

            h2.addComponent(v21);
            
            VerticalLayout v22 = new VerticalLayout();
            v22.setSpacing(true);
            h2.addComponent(v22);
            
            VerticalLayout v23 = new VerticalLayout();
            v23.setSpacing(true);

                v23.addComponent(support);
                
                v23.addComponent(confidence);

            h2.addComponent(v23);
            
        h.addComponent(h2);
            
        this.addComponent(h);
    }
        
    private boolean hasDefinedAssociation(String indicator) {
        return definedAssociationsTextArea.getValue().toString().contains(indicator);
    }
    
    private void addToDefinedAssociation(String indicator) {
        if (!hasDefinedAssociation(indicator))
            definedAssociationsTextArea.setValue(definedAssociationsTextArea.getValue() + indicator + separator);
    }

}
